﻿using System.Linq;
using ContactCenter.Core.Common;
using ContactCenter.Core.ObjectModel;
using NHibernate;
using NHibernate.Cfg;
using StructureMap;

namespace ContactCenter.Persistence.NH
{
    public class SessionFactoryCreatorJob : IBootstrapperJob
    {
        private readonly IContainer _container;

        public SessionFactoryCreatorJob(IContainer container)
        {
            _container = container;
        }

        #region IBootstrapperJob Members

        public int Position
        {
            get { return 1; }
        }

        public void Execute()
        {
            var tasks = _container.GetAllInstances<IConfigurationTask<Configuration>>().OrderBy(x => x.Position);

            var configuration = TaskExecutor.Execute(tasks.ToArray());

            _container.Configure(c =>
                                     {
                                         c.ForSingletonOf<Configuration>().Use(configuration);
                                         c.ForSingletonOf<ISessionFactory>().Use( x => configuration.BuildSessionFactory());
                                         c.For<ISession>().Use(x => x.GetInstance<ISessionFactory>().GetCurrentSession());
                                     });
        }

        #endregion
    }
}